package com.mystudy.leetcode.problem.link.p_21;

//import com.mystudy.leetcode.base.ListNode;

import com.mystudy.leetcode.base.ListNode;
import com.mystudy.leetcode.base.ListNodeUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/7/4 21:50
 * @Description 合并两个有序链表
 */
public class Solution {
    private static final Logger LOGGER = LoggerFactory.getLogger(Solution.class);
    


    @Test
    public void testMerge(){
        ListNode l1 = ListNodeUtils.generateLinkList(new int[]{1, 2, 4});
        ListNode cur1 = l1;
        StringBuilder sb1 = new StringBuilder();
        while(cur1 != null){
            sb1.append(cur1.val+"->");
            cur1 = cur1.next;
        }
        LOGGER.debug("sb1 = [ {} ]",sb1.toString());

        ListNode l2 = ListNodeUtils.generateLinkList(new int[]{1, 3, 4});
        ListNode cur2 = l1;
        StringBuilder sb2 = new StringBuilder();
        while(cur2 != null){
            sb2.append(cur2.val+"->");
            cur2 = cur2.next;
        }
        LOGGER.debug("sb2 = [ {} ]",sb2.toString());


        ListNode listNode = mergeTwoLists(l1, l2);
        LOGGER.debug("listNode = [ {} ]",listNode.val);
        LOGGER.debug("listNode = [ {} ]",listNode.next.val);
        LOGGER.debug("listNode = [ {} ]",listNode.next.next.val);
        LOGGER.debug("listNode = [ {} ]",listNode.next.next.next.val);
        LOGGER.debug("listNode = [ {} ]",listNode.next.next.next.next.val);
        LOGGER.debug("listNode = [ {} ]",listNode.next.next.next.next.next.val);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        if(l1.val <=l2.val){
            l1.next = mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }

    }
}
